package com.heer.gymnasium.module.main.views;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.api.constants.IConstants;
import com.heer.gymnasium.base.BaseFragment;
import com.heer.gymnasium.module.advise.beans.AdMainBean;
import com.heer.gymnasium.module.article.beans.ArticleBean;
import com.heer.gymnasium.module.article.beans.ArticleFirstBean;
import com.heer.gymnasium.module.article.beans.ArticleResponseBean;
import com.heer.gymnasium.module.coach.beans.CoachResponseBean;
import com.heer.gymnasium.module.common.beans.TypeValue;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.adapters.HomeAdapter;
import com.heer.gymnasium.module.coach.beans.CoachBean;
import com.heer.gymnasium.module.main.beans.BannerResponseBean;
import com.heer.gymnasium.module.main.beans.CategoryBean;
import com.heer.gymnasium.module.map.views.LocationSetActivity;
import com.heer.gymnasium.module.store.beans.StoreBean;
import com.heer.gymnasium.module.store.beans.StoreResponseBean;
import com.heer.gymnasium.module.store.views.StoreListActivity;
import com.heer.gymnasium.util.KeyBoardUtils;
import com.heer.imagepick.DensityUtils;
import com.zbar.lib.activity.CaptureActivity;
import com.zhihuiyun.library.utils.L;
import com.zhihuiyun.library.utils.SPUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by yan on 2018/1/11.
 * 首页Fragment
 */

public class HomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, TypeValue {
    private final static int LAYOUT = R.layout.layout_home;
    private final static int RES_RIGHT = R.id.layout_title_search_bar_right_iv;
    private final static int RES_LEFT = R.id.layout_title_search_bar_left_tv;
    private final static int RES_LEFT_IV = R.id.layout_title_search_bar_left_iv;

    private final int RES_ID_LAYOUT_CATEGORY = R.layout.item_category;
    private final static int RES_ID_SEARCH = R.id.layout_title_search_bar_search_iv;


    @BindView(RES_ID_REFRESH_LAYOUT)
    SwipeRefreshLayout refreshLayout;
    @BindView(RES_ID_RECYCLER_VIEW)
    RecyclerView recyclerView;
    @BindView(RES_RIGHT)
    ImageView rightTextView;
    @BindView(RES_LEFT)
    TextView leftTextView;
    @BindView(RES_LEFT_IV)
    ImageView leftImageView;
    @BindView(RES_ID_SEARCH_BAR_ET)
    EditText searchEditText;

    private HomeAdapter homeAdapter;

    @Override
    protected int setConvertView() {
        return LAYOUT;
    }

    @Override
    protected void init() {
        super.init();
    }


    @Override
    protected void initView() {
        super.initView();
        rightTextView.setVisibility(View.VISIBLE);

        leftTextView.setText(SPUtils.get(this.getActivity(), SPUtils.SP_ADNAME, "河北区").toString());
        leftImageView.setImageResource(R.drawable.ic_location_normal);
        leftImageView.getLayoutParams().width = DensityUtils.dip2px(getContext(), 20);
        leftImageView.getLayoutParams().height = DensityUtils.dip2px(getContext(), 20);
        refreshLayout.setOnRefreshListener(this);

        homeAdapter = new HomeAdapter(getContext());
        recyclerView.setAdapter(homeAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    ToastUtil.show(getContext(), v.getText().toString());
                    doSearch();
                    KeyBoardUtils.closeKeyboardWithoutFinish((Activity) getContext());
                }
                return false;
            }
        });
    }


    @Override
    protected void loadData() {
        super.loadData();
        getBannerList();
        getCategoryList();
        getAd("4");
        getAd("5");
        getArticleFirst();
        getArticleList();
        getStadiumList();
        getCoachList();
    }


    //获取文章列表
    private void getBannerList() {
        mAppHelper.apiService().getBannerList("1").enqueue(new BaseCallback<ApiResponse<List<BannerResponseBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<BannerResponseBean>>> call, Response<ApiResponse<List<BannerResponseBean>>> response) {
                setRefresh(false);
                if (response.isSuccessful() && response.body().isSccessful()) {
                    List<BannerResponseBean> been = response.body().getData();
                    homeAdapter.setBannerData(BannerResponseBean.dataChange(been));
                }
            }

            @Override
            public void onError(Call<ApiResponse<List<BannerResponseBean>>> call, Throwable t) {
                super.onError(call, t);
                setRefresh(false);
            }

            @Override
            public void onFailure(Call<ApiResponse<List<BannerResponseBean>>> call, Throwable t) {
                super.onFailure(call, t);
                setRefresh(false);
            }
        });
    }

    //获取文章列表
    private void getArticleList() {
        mAppHelper.apiService().getArticleList("1", "1", null).enqueue(new BaseCallback<ApiResponse<ArticleResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<ArticleResponseBean>> call, Response<ApiResponse<ArticleResponseBean>> response) {
                if (response.isSuccessful() && response.body().isSccessful()) {
                    homeAdapter.setArticleList(ArticleBean.dataChange(response.body().getData().getData()));
                }
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    //获取店铺列表
    private void getStadiumList() {
        SignHelper signHelper = new SignHelper("");
        mAppHelper.apiService().getStadiumList("1", null, SPUtils.get(this.getActivity(), SPUtils.SP_LA, IConstants.LA).toString(),
                SPUtils.get(this.getActivity(), SPUtils.SP_LO, IConstants.LO).toString(), null,
                "", null).enqueue(new BaseCallback<ApiResponse<StoreResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<StoreResponseBean>> call, Response<ApiResponse<StoreResponseBean>> response) {
                if (response.isSuccessful() && response.body().isSccessful()) {
                    homeAdapter.setStoreList(StoreBean.dataChange(response.body().getData().getData()));
                }
            }

            @Override
            public void onTokenTimeOut() {
            }


        });
    }

    //获取私教列表
    private void getCoachList() {
        mAppHelper.apiService().getCoachList("1", "", null, null, null, null, null).enqueue(new BaseCallback<ApiResponse<CoachResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<CoachResponseBean>> call, Response<ApiResponse<CoachResponseBean>> response) {
                if (response.isSuccessful() && response.body().isSccessful()) {
                    homeAdapter.setCoachList(CoachBean.dataChange(response.body().getData().getData()));
                }
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    //获取广告
    private void getAd(final String type) {
        mAppHelper.apiService().getAd(type).enqueue(new BaseCallback<ApiResponse<AdMainBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<AdMainBean>> call, Response<ApiResponse<AdMainBean>> response) {
                if (response.isSuccessful() && response.body().isSccessful()) {
                    if (Integer.parseInt(type) == four) {
                        homeAdapter.setStoreAd(response.body().getData());
                    } else if (Integer.parseInt(type) == five) {
                        homeAdapter.setCoachAd(response.body().getData());

                    }
                }

            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    //获取咨询banner第一个
    private void getArticleFirst() {
        SignHelper sign = new SignHelper("");
        mAppHelper.apiService().getArticleFirst(sign.GetParameter("key")).enqueue(new BaseCallback<ApiResponse<ArticleFirstBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<ArticleFirstBean>> call, Response<ApiResponse<ArticleFirstBean>> response) {
                homeAdapter.setArticleAd(AdMainBean.firstBeanChangeBean(response.body().getData()));
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    //获取区域列表
    private void getCategoryList() {
        mAppHelper.apiService().getCategoryList("").enqueue(new BaseCallback<ApiResponse<List<CategoryBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<CategoryBean>>> call, Response<ApiResponse<List<CategoryBean>>> response) {
                homeAdapter.setCatogeryData(response.body().getData());
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    private void setRefresh(boolean flag) {
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(flag);
        }
    }

    @Override
    public void onRefresh() {
        loadData();
    }

    @OnClick(R.id.back)
    public void onCityClick() {
        Intent intent = new Intent(this.getActivity(), LocationSetActivity.class);
        startActivityForResult(intent, 2);
    }

    @OnClick(R.id.layout_title_search_bar_right_iv)
    public void onScanClick() {
        Intent intent = new Intent(this.getActivity(), CaptureActivity.class);
        getActivity().startActivityForResult(intent, 1);
    }

    @OnClick(RES_ID_SEARCH)
    public void doSearch() {
        if (!TextUtils.isEmpty(searchEditText.getText().toString())) {
            StoreListActivity.startActivity(getContext(), searchEditText.getText().toString());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationSetActivity.REQUSTCODE) {
            if (resultCode == RESULT_OK || resultCode == LocationSetActivity.RESULTCODE_LOCATION) {
                leftTextView.setText(data.getStringExtra(EXTRA_DATA));
                getStadiumList();
            }
        }
    }
}
